package com.sc.common.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author wu
 * @date 2018/07/23
 * @Description:
 */
public class JsonUtil {
    public static Object jsonToObj(String jsonObj, Class clazz) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Object obj = gson.fromJson(jsonObj, clazz);
        return obj;
    }

    public static Object jsonToObj(String jsonObj, Type type) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Object obj = gson.fromJson(jsonObj, type);
        return obj;
    }

    public <T> List<T> jsonToPojo(String jsonObj, Class clazz) {
        if (StringUtils.isBlank(jsonObj)) {
            return null;
        }
        Type t = clazz;
        Type type = new ParameterizedTypeImpl(clazz);
        List<T> list = new Gson().fromJson(jsonObj, type);
        return list;
    }
//
//    public <T> T jsonToPojoSingle(String jsonObj, Class clazz) {
//        if (StringUtils.isBlank(jsonObj)) {
//            return null;
//        }
//        Type t = clazz;
//        Type type = new ParameterizedTypeImpl(clazz);
//        return new Gson().fromJson(jsonObj, type);
//    }

    private class ParameterizedTypeImpl implements ParameterizedType {
        Class clazz;

        public ParameterizedTypeImpl(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }


}
